// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CopyDatabaseStep.cs" company="">
//   
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace ExecutionTool.CopyDatabase
{
    using System;

    using ExecutionTool.Common;
    using ExecutionTool.Profile;

    using Microsoft.Practices.EnterpriseLibrary.Logging;

    public class CopyDatabaseStep : StepBase<CopyDatabaseStepInfo>
    {
        #region Fields

        private readonly ISqlAzureAdapter adapter;

        private CopyDatabaseStepInfo copyDatabaseStepInfo;

        #endregion

        #region Constructors and Destructors

        public CopyDatabaseStep(Profile profile, ISqlAzureAdapter adapter, LogWriter logger, double? progressHeartbeatInterval = null)
            : base(profile, true, logger, progressHeartbeatInterval)
        {
            Helper.CheckForNull(adapter, "adapter");

            this.adapter = adapter;
        }

        public CopyDatabaseStep(Profile profile, ISqlAzureAdapter adapter, double? progressHeartbeatInterval = null)
            : this(profile, adapter, null, progressHeartbeatInterval)
        {
        }

        #endregion

        #region Methods

        protected override void AbortAction()
        {
            if (this.copyDatabaseStepInfo != null)
            {
                this.adapter.DeleteDatabase(this.Profile.Source, this.copyDatabaseStepInfo.TargetDatabaseName);
            }
        }

        protected override void CleanupAction()
        {
            // for this step, Cleanup happens to be the same action as Abort
            this.AbortAction();
        }

        protected override double ProgressHeartbeatAction()
        {
            var newProgress = this.adapter.GetCopyDatabaseProgress(this.Profile.Source, this.copyDatabaseStepInfo.TargetDatabaseName);
            return newProgress;
        }

        protected override CopyDatabaseStepInfo StartAction()
        {
            var targetDatabaseName = Guid.NewGuid().ToString("D");
            this.adapter.StartCopyDatabase(this.Profile.Source, targetDatabaseName);
            var editionCapInfo = this.adapter.GetDatabaseInfo(this.Profile.Source);
            this.copyDatabaseStepInfo = new CopyDatabaseStepInfo(editionCapInfo, targetDatabaseName);
            return this.copyDatabaseStepInfo;
        }

        #endregion
    }
}
